﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using YawetagLib.Utilities;

namespace YawetagLib.Web.Utilities
{
    public static class Extensions
    {
        public static IEnumerable<object> GetModelErrors(this IDictionary<string, ModelState> modelState)
        {
            foreach (string modelKey in modelState.Keys)
            {
                foreach (ModelError e in modelState[modelKey].Errors)
                {
                    yield return new { Key = modelKey, e.ErrorMessage };
                }
            }
        }

        public static string ToTagHtmlAttributes(this object htmlAttributes)
        {
            if (htmlAttributes != null)
            {
                StringBuilder builder = new StringBuilder();
                htmlAttributes.ForEachPropertyNameAndValue((p, v) => builder.AppendFormat(string.Format("{0}=\"{1}\"", p, v.ToString()) + " "));

                return builder.ToString().Trim();
            }

            return string.Empty;
        }

        public static IEnumerable<SelectListItem> ToSelectList(this IEnumerable<SelectListItem> items, object selectedValue)
        {
            return selectedValue != null ? new SelectList(items, "Value", "Text", selectedValue) : items;
        }

        public static IEnumerable<SelectListItem> ToSelectListItems(this IEnumerable<string> items)
        {
            return items.Select((i, index) => new SelectListItem { Value = (index + 1).ToString(), Text = i });
        }

        public static IEnumerable<SelectListItem> WithBlankItem(this IEnumerable<SelectListItem> items, string blankItem) 
        {
            return !string.IsNullOrEmpty(blankItem)
                ? new[] { new SelectListItem { Value = string.Empty, Text = blankItem } }.Concat(items)
                : items;
        }
    }
}
